﻿using Youz.Common.Entity;
using Youz.Common.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Security;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Youz.Common.BLL
{
    public class Utility
    {
        private static Log_ErrorLogBLL errorBLL = new Log_ErrorLogBLL();
        private static Log_LoginLogBLL loginBLL = new Log_LoginLogBLL();
        private static Log_OperationLogBLL operationLogBLL = new Log_OperationLogBLL();
        private static Sys_StatusRecordBLL statusRecordBLL = new Sys_StatusRecordBLL();

        #region 属性
        /// <summary>
        /// 獲取當前語言下的日期格式
        /// </summary>
        public static string CurrentDataFormat
        {
            get
            {
                Lang_LanguageType type = CurrentLanguageType;
                return type == null ? "yyyy-MM-dd" : type.DateFormat;
            }
        }

        /// <summary>
        /// 獲取當前語言下的日期時間格式
        /// </summary>
        public static string CurrentDataTimeFormat
        {
            get
            {
                return string.Format("{0} HH:mm:ss", CurrentDataFormat);
            }
        }

        /// <summary>
        /// 当前语言
        /// </summary>
        public static string CurrentLanguage
        {
            get
            {
                if (String.IsNullOrEmpty(CookieHelper.GetCookie("Language")))
                {
                    Lang_LanguageType type = new Lang_LanguageTypeBLL().GetDefault();
                    if (type != null)
                    {
                        return Convert.ToString(type.LanguageCode);
                    }
                }

                return CookieHelper.GetCookie("Language");
            }
            set { CookieHelper.SetCookie("Language", value); }
        }

        /// <summary>
        /// 当前语言类型
        /// </summary>
        /// <summary>
        /// 当前语言类型
        /// </summary>
        public static Lang_LanguageType CurrentLanguageType
        {
            get
            {
                return new Lang_LanguageTypeBLL().Get(CurrentLanguage);
            }
        }

        /// <summary>
        /// 獲取當前登錄用戶的角色ID
        /// </summary>
        public static Guid CurrentRoleID
        {
            get
            {
                if (String.IsNullOrEmpty(CookieHelper.GetCookie("CurrentRoleID")))
                {
                    Guid roleID = Guid.Empty;
                    var memberRole = new Right_MemberRoleBLL().Get(MemberAccount, CurrentSiteType);
                    if (memberRole != null)
                    {
                        roleID = memberRole.RoleID;
                    }
                    else if (CurrentSiteType == SiteType.Web)
                    {
                        roleID = new Right_RoleinfoBLL().GetDefault();
                    }

                    CookieHelper.SetCookie("CurrentRoleID", roleID.ToString());

                    return roleID;
                }
                else
                {
                    return TypeHelper.ConvertTo<Guid>(CookieHelper.GetCookie("CurrentRoleID"));
                }
            }
        }

        /// <summary>
        /// 当前站点类型  1后台,2为前台,3为中心
        /// </summary>
        public static SiteType CurrentSiteType
        {
            get
            {
                return (SiteType)ConfigHelper.GetConfigInt("SiteType");
            }
        }

        /// <summary>
        /// 当前站点语言类型 1后台,2为前台,
        /// </summary>
        public static int CurrentSiteLanguageID
        {
            get
            {
                return ConfigHelper.GetConfigInt("LanguageID");
            }
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        public static bool IsLogin
        {
            get { return HttpContext.Current.User.Identity.IsAuthenticated; }
        }

        /// <summary>
        /// 会员帐号
        /// </summary>
        public static string MemberAccount
        {
            get
            {
                if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return HttpContext.Current.User.Identity.Name;

                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 會員最後登錄時間
        /// </summary>
        public static string MemberLastLoginedOn
        {
            get
            {
                if (String.IsNullOrEmpty(CookieHelper.GetCookie("MemberLastLoginedOn")))
                {
                    return null;
                }
                else
                {
                    return CookieHelper.GetCookie("MemberLastLoginedOn");
                }
            }
            set
            {
                CookieHelper.SetCookie("MemberLastLoginedOn", value);
            }
        }

        /// <summary>
        /// 會員登录ID
        /// </summary>
        public static Guid MemberLoginID
        {
            get
            {
                if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return TypeHelper.ConvertTo<Guid>(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData.Split(',')[0]);
                }
                else
                {
                    return Guid.Empty;
                }
            }
        }

        /// <summary>
        /// 会员姓名
        /// </summary>
        public static string MemberName
        {
            get
            {
                if (HttpContext.Current.User != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return ((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData.Split(',')[1];
                }
                else
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 会员邮箱
        /// </summary>
        public static string MemberEmail
        {
            get
            {
                if (HttpContext.Current.User != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return ((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData.Split(',')[2];
                }
                else
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 会员手机号
        /// </summary>
        public static string MemberMobile
        {
            get
            {
                if (HttpContext.Current.User != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return ((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData.Split(',')[3];
                }
                else
                {
                    return null;
                }
            }
        }
        #endregion

        #region 写入操作日志、登录日志、错误日志

        /// <summary>
        /// 系统错误日志
        /// </summary>
        /// <param name="_Source">错误发生的模块</param>
        /// <param name="_TargetSite">引发异常的方法</param>
        /// <param name="_errorInfo">错误信息</param>
        public static void WriteErrorLog(string _Source, string _TargetSite, string _errorInfo)
        {
            try
            {
                WriteErrorLog(_Source, _errorInfo, _errorInfo, _errorInfo, _errorInfo);
            }
            catch { }
        }

        /// <summary>
        /// 系统错误日志
        /// </summary>
        public static void WriteErrorLog(Exception ex)
        {
            try
            {
                WriteErrorLog(ex.Source, ex.TargetSite.ToString(), ex.Message, ex.GetBaseException().Message, ex.GetBaseException().StackTrace);
            }
            catch { }
        }

        /// <summary>
        /// 系统错误日志
        /// </summary>
        public static void WriteErrorLog(string _Source, string _TargetSite, string _Message, string _BaseErrMess, string _StackTrace)
        {
            try
            {
                Log_ErrorLog log = new Log_ErrorLog();
                log.ErrorLogID = Guid.NewGuid();
                log.Host = HttpContext.Current.Request.Url.Host;
                log.RequestType = HttpContext.Current.Request.RequestType;
                log.LoginType = (int)CurrentSiteType;
                log.AbsolutePath = HttpContext.Current.Request.Url.AbsolutePath;
                log.PostData = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Form.ToString());
                log.QueryString = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.QueryString.ToString());
                log.UserHostAddress = Youz.Common.Helper.IPHelp.GetClientIPv4Address();
                log.UserAgent = HttpContext.Current.Request.UserAgent;
                log.Source = _Source;                     //导致错误的应用程序或对象的名称
                log.TargetSite = _TargetSite;               //引发当前异常的方法
                log.ErrMess = HttpContext.Current.Server.HtmlEncode(_Message);
                log.BaseErrMess = HttpContext.Current.Server.HtmlEncode(_BaseErrMess);
                log.StackTraceErr = _StackTrace + "\r\n\r\nPostData:\r\n" + HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Form.ToString());
                log.CreateTime = ConfigParameters.SysTime;

                errorBLL.Add(log);
            }
            catch {
                Log_ErrorLog log = new Log_ErrorLog();
                log.ErrorLogID = Guid.NewGuid();
                log.LoginType = (int)CurrentSiteType;
                log.Source = _Source;                     //导致错误的应用程序或对象的名称
                log.TargetSite = _TargetSite;               //引发当前异常的方法
                log.ErrMess = _Message;
                log.BaseErrMess = _BaseErrMess;
                log.StackTraceErr = _StackTrace;
                log.CreateTime = DateTime.Now;

                errorBLL.Add(log);
            }
        }

        /// <summary>
        /// 系统登录日志
        /// </summary>
        /// <param name="_IsSuccess">是否成功</param>
        /// <param name="LoginType">登录类型  1：后台管理  2：前台站点</param>
        /// <param name="_Memo">备注信息</param>
        public static string WriteLoginLog(bool _IsSuccess, string account, int LoginType, string _Memo)
        {
            Log_LoginLog model = new Log_LoginLog();

            model.LoginID = Guid.NewGuid();
            model.MemberAccount = account;
            model.LoginIP = IPHelp.GetClientIPv4Address();
            model.UserAgent = HttpContext.Current.Request.UserAgent;
            model.IsSuccess = _IsSuccess;
            model.LoginType = LoginType;
            model.Memo = _Memo;
            model.CreateDate = ConfigParameters.SysTime;

            loginBLL.Add(model);

            return model.LoginID.ToString();
        }

        /// <summary>
        /// 写入操作日志
        /// </summary>
        /// <param name="context">this.Page</param>
        /// <param name="ModuleName">模块名</param>
        /// <param name="FunctionName">功能名</param>
        /// <param name="_OperationContent">操作内容</param>
        public static void WriteOperationLog(string ModuleName, string FunctionName, string _OperationContent, int Sensitive = 0, string OperatingDetails = "")
        {
            Log_OperationLog model = new Log_OperationLog();

            model.OperationID = Guid.NewGuid();
            model.LoginID = MemberLoginID;
            model.LoginType = (int)CurrentSiteType;
            model.FunctionName = FunctionName;
            model.ModuleName = ModuleName;

            try
            {
                model.MemberAccount = MemberAccount ?? IPHelp.GetClientIPv4Address();
                model.URI = HttpContext.Current.Request.Url.ToString();
                model.PostData = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Form.ToString());
            }
            catch
            {
                model.MemberAccount = string.Empty;
                model.URI = string.Empty;
                model.PostData = string.Empty;
            }

            model.OperationContent = _OperationContent;
            model.CreateTime = DateTime.Now;
            model.Sensitive = Sensitive;
            model.OperatingDetails = OperatingDetails;

            operationLogBLL.Add(model);
        }

        public static void WriteOperationLog(string _MenuName, string _ModuleName, string type, bool result, string log, int Sensitive = 0, string OperatingDetails = "")
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(type);

            if (result)
            {
                sb.Append("成功");
            }
            else
            {
                sb.Append("失敗");
            }

            sb.AppendFormat(" {0}", log);

            WriteOperationLog(_MenuName, _ModuleName, sb.ToString(), Sensitive, OperatingDetails);
        }

        public static void WriteOperationLog(string _MenuName, string _ModuleName, OperationType type, bool result, string log)
        {
            WriteOperationLog(_MenuName, _ModuleName, type.ToString(), result, log);
        }

        #endregion

        #region 增加状态变更记录
        /// <summary>
        /// 增加状态变更记录
        /// </summary>
        /// <param name="module"></param>
        /// <param name="recordType"></param>
        /// <param name="memberAccount"></param>
        /// <param name="objID"></param>
        /// <param name="lastValue"></param>
        /// <param name="currentValue"></param>
        /// <param name="memo"></param>
        /// <returns></returns>
        public static bool AddStatusLog(LanguageModule module, string recordType, string memberAccount, object objID, int lastValue, int currentValue, string memo)
        {
            Sys_StatusRecord model = new Sys_StatusRecord
            {
                RecordId = Guid.NewGuid(),
                RecordTable = module.ToString(),
                RecordType = recordType,
                AfterValue = currentValue,
                BeforeValue = lastValue,
                MemberAccount = memberAccount,
                ObjectID = objID.ToString(),
                Memo = memo,
                CreateTime = DateTime.Now,
                Creator = MemberAccount,
                LoginID = MemberLoginID
            };

            return statusRecordBLL.Add(model);
        }

        /// <summary>
        /// 增加状态变更记录
        /// </summary>
        /// <param name="module"></param>
        /// <param name="memberAccount"></param>
        /// <param name="objID"></param>
        /// <param name="currentValue"></param>
        /// <param name="memo"></param>
        /// <returns></returns>
        public static bool AddStatusLog(LanguageModule module, string memberAccount, object objID, int currentValue, string memo)
        {
            return AddStatusLog(module, "Status", memberAccount, objID, 0, currentValue, memo);
        }

        /// <summary>
        /// 增加状态变更记录
        /// </summary>
        /// <param name="module"></param>
        /// <param name="memberAccount"></param>
        /// <param name="objID"></param>
        /// <param name="currentValue"></param>
        /// <returns></returns>
        public static bool AddStatusLog(LanguageModule module, string memberAccount, object objID, int currentValue)
        {
            return AddStatusLog(module, memberAccount, objID, currentValue, string.Empty);
        }
        #endregion

        #region Ajax返回结果
        public static string AjaxResult(bool isSuccess)
        {
            return AjaxResult(isSuccess, isSuccess ? "" : "操作失败，请检查您的输入");
        }

        /// <summary>
        /// 返回ajax请求处理结果json
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string AjaxResult(bool isSuccess, string message)
        {
            return GetJsonByObject(new { isSuccess = isSuccess, message = message });
        }

        public static string AjaxResult(bool isSuccess, string message, object data)
        {
            return GetJsonByObjectHaveTime(new { isSuccess = isSuccess, message = message, data = data });
        }

        /// <summary>
        /// 返回ajax请求处理结果json
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string AjaxResult(bool isSuccess, AjaxResultType type)
        {
            string message = string.Empty;

            switch (type)
            {
                case AjaxResultType.Save:
                    message = isSuccess ? Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_Save_Success", "信息保存成功。") : Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_Save_Error", "保存失败，请检查您的输入。");
                    break;
                case AjaxResultType.Delete:
                    message = isSuccess ? Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_Delete_Success", "删除成功。") : Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_Delete_Error", "删除失败，请检查您的输入或联系管理员。");
                    break;
                case AjaxResultType.EmailSend:
                    message = isSuccess ? Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_EmailSend_Success", "发送完成")
                    : Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_EmailSend_Error", "邮件发送中出现异常");
                    break;
                case AjaxResultType.AuditStatus:
                    message = isSuccess ? "" : Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Common, "AjaxResult_AuditStatus_Error", "审核失败，请检查您的输入或状态已变更。");
                    break;
            }

            return AjaxResult(isSuccess, message);
        }
        #endregion

        #region FormatDate
        /// <summary>
        /// 根據網站語言格式化日期
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static string FormatDate(DateTime datetime)
        {
            return CommonHelper.GetStandardDateTime(datetime.ToString(), CurrentDataFormat);
        }

        /// <summary>
        /// 根據網站語言格式化日期
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static string FormatDate(string datetime)
        {
            return CommonHelper.GetStandardDateTime(datetime.ToString(), CurrentDataFormat);
        }

        /// <summary>
        /// 根據網站語言格式化日期時間
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static string FormatDateTime(DateTime datetime)
        {
            return CommonHelper.GetStandardDateTime(datetime.ToString(), CurrentDataTimeFormat);
        }
        #endregion

        #region GetJson
        /// <summary>
        /// 把DataTable数据转换成分页json的格式
        /// 時間格式為yyyy-MM-dd
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>json格式的字符串</returns>
        public static string GetJsonByDataTable(int total, DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "{\"recordsTotal\":0,\"recordsFiltered\":0,\"data\":[]}";
            }
            return "{\"recordsTotal\":" + total + ",\"recordsFiltered\":" + total + ",\"data\":" + SerializeObject(dt) + "}";
        }

        /// <summary>
        /// 把对象数据转换成json的格式，时间采用yyyy-MM-dd
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJsonByList(object obj)
        {
            if (obj == null)
            {
                return "{\"data\":[]}";
            }
            return "{\"data\":" + SerializeObject(obj) + "}";
        }

        public static string GetJsonByObject(object obj)
        {
            return SerializeObject(obj);
        }

        public static string SerializeObject(object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = CurrentDataFormat;
            return JsonConvert.SerializeObject(obj, Formatting.Indented, timeConverter);
        }

        /// <summary>
        /// 把dataset数据转换成分页json的格式
        /// 時間格式为yyyy-MM-dd HH:mm:ss
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>json格式的字符串</returns>
        public static string GetJsonByDataTableHaveTime(int total, DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "{\"recordsTotal\":0,\"recordsFiltered\":0,\"data\":[]}";
            }
            return "{\"recordsTotal\":" + total + ",\"recordsFiltered\":" + total + ",\"data\":" + SerializeObjectByHaveTime(dt) + "}";
        }
        /// <summary>
        /// 把dataset数据转换成分页json的格式
        /// 時間格式为yyyy-MM-dd HH:mm:ss
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>json格式的字符串</returns>
        public static string GetPageByDataTableHaveTime(int total, DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "{\"total\":0,\"rows\":[]}";
            }
            return "{\"total\":" + total + ",\"rows\":" + GetJsonByObjectHaveTime(dt) + "}";
        }
        public static string GetJsonByListHaveTime(object obj)
        {
            if (obj == null)
            {
                return "{\"data\":[]}";
            }
            return "{\"data\":" + SerializeObjectByHaveTime(obj) + "}";
        }

        /// <summary>
        /// 把对象数据转换成json的格式，时间采用yyyy-MM-dd HH:mm:ss
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJsonByObjectHaveTime(object obj)
        {
            return SerializeObjectByHaveTime(obj);
        }

        /// <summary>
        /// 把对象数据转换成json的格式，时间采用yyyy-MM-dd HH:mm:ss
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObjectByHaveTime(object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = CurrentDataTimeFormat;

            return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonConverter[] { timeConverter });
        }
        #endregion

        public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
        {
            return JsonConvert.DeserializeAnonymousType<T>(value, anonymousTypeObject);
        }

        public static T DeserializeObject<T>(string value)
        {
            return JsonConvert.DeserializeObject<T>(value);
        }

        public static bool SafeString(string Parameter)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(Parameter, @"<script[^>]*?>.*?</script>"))
            {
                return true;
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(Parameter, @"<(.[^>]*)>"))
            {
                return true;
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(Parameter, @"([\r\n])[\s]+"))
            {
                return true;
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(Parameter, "<"))
            {
                return true;
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(Parameter, ">"))
            {
                return true;
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(Parameter, "\r\n"))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="context"></param>
        /// <param name="imageControlName">图片控件名称</param>
        /// <param name="uploadPath">上传保存目录</param>
        /// <param name="imageName">图片保存名</param>
        /// <returns>错误信息</returns>
        public static string UploadImage(HttpContext context, string imageControlName, string uploadPath, out string imageName)
        {
            imageName = string.Empty;

            if (!WebHelper.IsSelfRequest())
            {
                return Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "IllegalRequestSource", "非法的請求來源");
            }
            if (!WebHelper.HasFiles(new HttpRequestWrapper(context.Request)))
            {
                return Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "ChooseImgUpload", "請選擇圖片上傳");
            }

            HttpPostedFile img = context.Request.Files[imageControlName];

            if (string.IsNullOrWhiteSpace(WebHelper.GetFileExtension(img)) || !ValidationHelper.IsAllowedExtension(img, new FileExtension[] { FileExtension.JPG, FileExtension.GIF, FileExtension.PNG }))
            {
                return Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "IllegalImgFormat", "非法的圖片格式");
            }
            if (img.ContentLength > 1024 * 1024 * 5)
            {
                return Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "ImgSizeMaxDesc", "圖片大小不能大於5MB");
            }
            Bitmap bitmap;
            try
            {
                bitmap = new Bitmap(img.InputStream);
            }
            catch
            {
                return Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "UploadFailureDesc", "上傳失敗，非法的圖片格式");
            }

            imageName = string.Format("{0}.{1}", ConfigParameters.SysTime.Ticks.ToString(), WebHelper.GetFileExtension(img));

            string dir = "/UpLoad/" + (string.IsNullOrEmpty(uploadPath) ? "" : uploadPath + "/") + DateTime.Now.ToString("yyyy/MM/dd/");
            string imgPath = UrlHelper.GetMapPathPath(dir + imageName);

            bitmap.Save(imgPath);
            bitmap.Dispose();
            imageName = dir + imageName;

            return string.Empty;
        }

        public static string UploadImage(string imageControlName, string uploadPath, out string imageName)
        {
            return UploadImage(HttpContext.Current, imageControlName, uploadPath, out imageName);
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="imageControlName">图片控件名称</param>
        /// <param name="imageName">imageName</param>
        /// <returns>错误信息</returns>
        public static string UploadImage(string imageControlName, out string imageName)
        {
            return UploadImage(HttpContext.Current, imageControlName, string.Empty, out imageName);
        }

        public static ReturnMessage UploadFile(HttpContext context, string controlName, string uploadPath, FileExtension[] allowFileExtension)
        {
            var saveFileName = string.Empty;

            if (!WebHelper.IsSelfRequest())
            {
                return new ReturnMessage(false, Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "IllegalRequestSource", "非法的請求來源"));
            }
            if (!WebHelper.HasFiles(new HttpRequestWrapper(context.Request)))
            {
                return new ReturnMessage(false, Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "CheckFileEmpty", "请选择文件"));
            }

            HttpPostedFile file = context.Request.Files[controlName];

            if (!ValidationHelper.IsAllowedExtension(file, allowFileExtension))
            {
                return new ReturnMessage(false, Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "CheckFileFormat", "非法的文件格式"));
            }
            if (file.ContentLength > 1024 * 1024 * 5)
            {
                return new ReturnMessage(false, Lang_LanguageBLL.LanguageByWebSite(LanguageModule.M_Common, "CheckFileMaxSize", "文件不能大于5MB"));
            }
            
            saveFileName = string.Format("{0}.{1}", ConfigParameters.SysTime.Ticks.ToString(), WebHelper.GetFileExtension(file));

            string dir = "/UpLoad/" + (string.IsNullOrEmpty(uploadPath) ? "" : uploadPath + "/");
            string imgPath = UrlHelper.GetMapPathPath(dir + saveFileName);

            file.SaveAs(imgPath);

            saveFileName = dir + saveFileName;

            return new ReturnMessage(true, "文件上传成功", saveFileName);
        }

        public static ReturnMessage UploadAppPackage(HttpContext context, string controlName)
        { 
            string uploadPath = "AppPackage";
            FileExtension[] allowFileExtension = { FileExtension.APK, FileExtension.WGT };

            return UploadFile(context, controlName, uploadPath, allowFileExtension);
        }

        /// <summary>
        /// 保留小数位
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static decimal Round(decimal d)
        {
            return Math.Round(d, 2);
        }
        /// <summary>
        /// 读取枚举描述
        /// </summary>  [System.ComponentModel.Description("提现不通过")]
        /// <param name="enumValue">枚举值 </param>
        /// <returns></returns>
        public static string GetEnumDescription(Enum enumValue)
        {
            string str = enumValue.ToString();
            System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
            object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            if (objs == null || objs.Length == 0) return str;
            System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
            return da.Description;
        }

        /// <summary>
        /// 验证页面请求权限
        /// </summary>
        public static void AuthRequest()
        {
            Guid roleID = TypeHelper.ConvertTo<Guid>(CurrentRoleID);

            if (!Right_RoleRightBLL.Auth(roleID))
            {
                var url = WebHelper.CurrentRawUrl;
                var msg = Lang_LanguageBLL.LanguageByManage(LanguageModule.Right_RoleRight, "AuthRequest", "对不起，您不具有访问该页面的权限，请联系管理员！");

                if (url.Contains(".ashx"))
                {
                    HttpContext.Current.Response.Write(AjaxResult(false, msg));
                }
                else
                {
                    HttpContext.Current.Response.Write(msg);
                }
                HttpContext.Current.Response.End();
            }
        }
    }
}
